<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'"
             :close-on-click-modal="false"
             :visible.sync="visible">
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="姓名"
                    prop="name">
        <el-input v-model="dataForm.name"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="微信号" prop="wx">
        <el-input v-model="dataForm.wx" placeholder="请输入微信号"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer"
          class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary"
                 @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { isEmail, isMobile } from '@/utils/validate'
  export default {
    data () {
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        roleList: [],
        dataForm: {
          id: null,
          name: null,
          mobile: '',
          wx: ''
        },
        dataRule: {
          name: [{
            required: true, message: '姓名不能为空', trigger: 'blur'
          }],
          mobile: [{
            required: true, message: '姓名不能为空', trigger: 'blur'
          }, {
            validator: validateMobile, trigger: 'blur'
          }],
          wx: [{
            required: true, message: '微信号不能为空', trigger: 'blur'
          }]
        }
      }
    },
    methods: {
      init (row) {
        console.log(row)
        this.dataForm.id = row ? row.id : 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.dataForm.name = row.name
            this.dataForm.mobile = row.mobile
            this.dataForm.wx = row.wx
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(this.dataForm.id ? '/agent/update' : '/agent/add'),
              method: this.dataForm.id ? 'put' : 'post',
              data: this.$http.adornData(this.dataForm)
            }).then(({ data }) => {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            })
          }
        })
      }
    }
  }
</script>
